package com.chris.getfile.core;


import com.chris.getfile.comm.IoUtil;
import com.chris.getfile.comm.JacksonUtil;
import com.chris.module.okhttp.OkHttpUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class HttpService {
    @Autowired
    OkHttpUtil okHttpUtil;

    @Autowired
    JacksonUtil jacksonUtil;
    IoUtil io = new IoUtil();
    OkHttpClient client;

    @Value("${chris.file_path:/}")
    private String file_path;

    @Value("${chris.file_url:/}")
    private String file_url;

    @Value("${chris.icount_s_file:/}")
    private int   icount_s_file= 38;
    @Value("${chris.icount_e_file:/}")
    private int   icount_e_file= 38;

    @Value("${chris.icount_s_download:/}")
    private int icount_s_download= 38;
    @Value("${chris.icount_e_download:/}")
    private int icount_e_download= 38;
    @Deprecated
    public void getpage() throws IOException {

        for (int i = 14; i <= 935; i++) {//
            String html = okHttpUtil.doGet("https://www.520101.com/html/mappaper/dvdpaper?page=" + i);
            int s = html.indexOf("<p class=\"title\">");
            int e = html.lastIndexOf("</a></p>");
            html = html.substring(s, e);
            String[] a = html.split("href=\"");
            List<String> list = new ArrayList<>();
            for (String tmp :
                    a) {
                int b = tmp.indexOf("\">");
                String c = tmp.substring(0, b);
                if (c.indexOf("/html") == 0)
                    list.add(c);
            }
            io.doWriteFile("E:\\test\\page\\" + i + ".txt", jacksonUtil.writeValueAsString(list));
            // System.out.println("s:"+s+"e:"+e+"html:"+html);
        }
    }


    /**
     * 获取下载文件txt
     */
    public void dopagefile()  {

        for (int i = icount_s_file; i <= icount_e_file; i++) {
            try {
                String html = io.doGetFile("E:\\test\\page\\" + i + ".txt");

                List<String> filelist = jacksonUtil.readValueToList(html);
                StringBuilder stringBuilder = new StringBuilder();
                for (String url :
                        filelist) {
                    String file = okHttpUtil.doGet("https://www.520101.com" + url);
                    int f_s = file.indexOf("down-tit\">");
                    int f_e = file.indexOf("<span class=\"label label-badge label-danger label-outline\"");
                    String file_name = file.substring(f_s + 10, f_e);
                    int d_s = file.indexOf("button\" href=\"");
                    int d_e = file.indexOf("\"><i class=\"icon icon-paper-clip\">");
                    if (d_s<= 0 || d_e<=0)
                        continue;
                    String dowload_url = file.substring(d_s + 14, d_e);
                    System.out.println(file_name);
                    System.out.println(dowload_url);
                    //stringBuilder.append("https://www.520101.com"+dowload_url+"@"+file_name);
                    stringBuilder.append("https://www.520101.com"+dowload_url+"@"+file_name+"\n");
                    //dw(file_name, dowload_url, i);
                }
                io.doWriteFile(file_url + i + ".txt", stringBuilder.toString());
            }
            catch (Exception ex)
            {
String aa= ex.toString();
            }
        }
    }

    /**
     * 下载文件
     */
    public void dowanloadfile()
    {
        for (int i = icount_s_download; i <= icount_e_download; i++) {
            try {
                String html = io.doGetFile(file_url + i + ".txt");
                //System.out.println(html);
                String[] urls = html.split("\n");
                for (String url :
                        urls) {
                    String[] s = url.split("@");
                    String file_name = s[1];
                    String dowload_url = s[0];
                    System.out.println(file_name);
                    System.out.println(dowload_url);
                    dw(file_name, dowload_url, i);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
    public void dowanloadfile_old()  {
        for (int i = 14; i <= 935; i++) {
            try {
                String html = io.doGetFile("E:\\test\\page\\" + i + ".txt");
                //System.out.println(html);
                List<String> filelist = jacksonUtil.readValueToList(html);
                for (String url :
                        filelist) {
                    String file = okHttpUtil.doGet("https://www.520101.com" + url);
                    int f_s = file.indexOf("down-tit\">");
                    int f_e = file.indexOf("<span class=\"label label-badge label-danger label-outline\"");
                    String file_name = file.substring(f_s + 10, f_e);
                    int d_s = file.indexOf("button\" href=\"");
                    int d_e = file.indexOf("\"><i class=\"icon icon-paper-clip\">");
                    String dowload_url = file.substring(d_s + 14, d_e);
                    System.out.println(file_name);
                    System.out.println(dowload_url);
                    dw(file_name, dowload_url, i);
                }
            }
            catch (Exception ex)
            {

            }
        }
    }

    /**
     * 下载文件
     * @param file_name
     * @param dowload_url
     * @param i
     */
    private void dw(String file_name, String dowload_url, int i) {
        //  String url = "https://www.520101.com/down/2310095825849198/2310091624801427";
        if (client == null) {
            // 创建一个 okhttp客户端线程池
            OkHttpClient.Builder builder = new OkHttpClient.Builder();

            //2022-7-15 重要： 当连接失败，尝试重连。组建默认保持5分钟连接，如果下一次连接还是相同url会默认调用原来的连接，但是如果对方客户端已经关闭
            //就会频繁出现  java.io.IOException: unexpected end of stream on ... 的错误
            //  builder.retryOnConnectionFailure(true);
            //  builder.connectionPool(ConnectionPool(Integer.MAX_VALUE, 60, TimeUnit.MINUTES));

            builder.connectTimeout(180, TimeUnit.SECONDS);
            builder.readTimeout(300, TimeUnit.SECONDS);
            builder.writeTimeout(300, TimeUnit.SECONDS);


            client = builder.build();
        }


        // 构建请求对象
        Request request = new Request.Builder().url(dowload_url).get().build();

        // 发起请求得到请求结果
        Response response = null;
        try {
            response = client.newCall(request).execute();


            // 获取请求结果
            ResponseBody responseBody = response.body();
            if (null != responseBody) {
                // 获取文件后缀类型 可以使用 responseBody.contentType() 获取 ContentType，我这边知道这个url文件的类型
                String suffix = ".pdf";
                int j = response.request().url().toString().lastIndexOf(".");
                suffix = response.request().url().toString().substring(j);
                // 创建一个文件
                String filename = file_path+ i + "/" + file_name.replace("/", "-").trim() + suffix;
                File file = new File(filename);

                // 判断目录是否存在，不存在则创建目录

                File parent = new File(file.getParent());
                if (!parent.exists()) {
                    parent.mkdir();
                }

                // 判断文件是否存在, 不存在创建文件
                //if (!file.exists()) { 不管时候存在，新建
                    try {
                        try {
                            file.createNewFile();
                        } catch (Exception ee) {
                            filename = file_path + i + "/" + System.currentTimeMillis() + suffix;
                            file = new File(filename);
                            file.createNewFile();
                        }
                        // 获取请求结果输入流
                        InputStream rInputStream = responseBody.byteStream();

                        // 创建读取字节流的byte数组
                        byte[] buffer = new byte[500];

                        int areRead;

                        // 创建文件输出流
                        FileOutputStream outputStream = new FileOutputStream(file);

                        // 使用输入流读取字节，在输出到文件
                        while ((areRead = rInputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, areRead);
                        }
                        rInputStream.close();
                        outputStream.close();

                    } catch (IOException e) {
                        // throw new RuntimeException(e);
                        System.out.println("出错i=" + i + " " + e.toString());
                    }
               // }
            }
            response.close();
        } catch (IOException e) {
            System.out.println("出错i=" + i + " " + e.toString());
            //throw new RuntimeException(e);
        }
    }
}
